package net.kleinhenz.questor.system;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipFile;

import org.simpleframework.xml.core.Persister;

import android.util.Log;

import net.kleinhenz.questor.Questor;
import net.kleinhenz.questor.model.Quest;

public class QSRFile
{
	// zip entries
	public static final String STORY = "story.xml";

	// unique numbering system for temp files
	public int number = -1;
	private static int tempNumber = 0; 
	private File cacheDir = null;

	// the zip file handled by this instance
	private ZipFile zipFile = null; 
	
	public QSRFile(File cacheDir, File file) throws IOException
	{
		this(cacheDir, new FileInputStream(file));
	}

	public QSRFile(File cacheDir, InputStream inputStream) throws IOException
	{
	    Log.i(Questor.APP_NAME, "Creating QSRFile instance fom input stream.");

		this.number = tempNumber++;
		this.cacheDir = cacheDir;
		File tempFile = new File(cacheDir.getAbsolutePath() + "/story" + number + ".qsr");

		BufferedInputStream input = new BufferedInputStream(inputStream);
		BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile));

		int read = -1;
		byte[] buf = new byte[1024];
		while ((read=input.read(buf))!=-1)
			output.write(buf, 0, read);
		output.close();
		input.close();

		zipFile = new ZipFile(tempFile);

	    Log.i(Questor.APP_NAME, "Finished creating QSRFile instance fom input stream.");
	}

	public InputStream getInputStream(String path) throws IOException
	{
		if (path.startsWith("/"))
			path=path.substring(1);
		return new BufferedInputStream(zipFile.getInputStream(zipFile.getEntry(path)));
	}

	public File getFile(String path) throws IOException
	{
		File tempFile = new File(cacheDir.getAbsolutePath() + "/story" + number + ".qsr" + "-" + path.replace('/', '%'));

		BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile));
		InputStream input = getInputStream(path);
		
		int read = -1;
		byte[] buf = new byte[1024];
		while ((read=input.read(buf))!=-1)
			output.write(buf, 0, read);
		output.close();
		input.close();
		
		return tempFile;
	}
	
	public Quest getStory() throws Exception
	{
		return new Persister().read(Quest.class, getInputStream(STORY));
	}
}
